//
//  UserAccountViewModel.swift
//  新浪微博01
//
//  Created by 李国伟 on 15/12/9.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import Foundation

class UserAccountViewModel{
    
    static let shareModel = UserAccountViewModel()
    
    var account :UserAccount?
    
    private  init() {
        
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount
        
        if isExpired {
            
            account = nil
        }
    }
    
    //判断是否过期
    private var isExpired: Bool{
        
        //判断是否比现在时间小
//        return account?.expireDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending
        if account?.expireDate != nil{
            return account?.expireDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending
        }
        
        return true
    }
    
    //判断是否又新版本更新
     var isNewVersion: Bool{
      
        //从主资源包拿到当前版本,版本只会比原来大不会原来小
        let curretVesion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as? String
        
        let oldVesion = (NSUserDefaults.standardUserDefaults().objectForKey("NowVesion") as? String) ?? ""
        
        //保存到本地
        NSUserDefaults.standardUserDefaults().setValue(curretVesion, forKey: "NowVesion")
        
        let isNew = curretVesion?.compare(oldVesion) == .OrderedDescending
        
        return isNew
    }
    
    //判断用户能否登录了
    var userlogin: Bool{
        return account?.access_token != nil && isExpired != true
    }
    
    //头像链接
    var largeRUL: NSURL{
       let  urlstring = NSURL(string: (account?.avatar_large) ?? "")
       return urlstring!
    }
    
    //令牌
    var tokenDict: [String: AnyObject]?{
        return isExpired ? nil: ["access_token": account!.access_token!]
    }
}

extension UserAccountViewModel{
    
    //加载
    func  loadToken(code: String,finshed:(isSuccess: Bool)->()){
        //获取令牌
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            
            if error != nil{
                print("出错")
                finshed(isSuccess: false)
                return
            }else{
                //字典转模型
                 self.account = UserAccount(dic: result as? [String: AnyObject])
                 self.loadUserInfo(self.account!,finshed: finshed)
            }
        }
    }
    
    //获取用户信息
    private func loadUserInfo(account :UserAccount,finshed:(isSuccess: Bool)->()){
        NetworkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
            if error != nil{
                print(error)
                finshed(isSuccess: false)
            }else{
                
                //创建出一个字典给useraccount初始化
                guard let dic = result as? [String :AnyObject] else{
                    
                    print("格式出错")
                    finshed(isSuccess: false)
                    return
                }
                
                //给用户模型重新赋值，并且进行归档
                account.screen_name = dic["screen_name"] as? String
                account.avatar_large = dic["avatar_large"] as? String
                NSKeyedArchiver.archiveRootObject(account, toFile: path)
                finshed(isSuccess: true)
            }
        }
    }
}

